package com.framework.tomcat.ex03.pyrmont.processor;

import com.framework.tomcat.ex03.pyrmont.Constants;
import com.framework.tomcat.ex03.pyrmont.Request;
import com.framework.tomcat.ex03.pyrmont.Response;
import com.framework.tomcat.ex03.pyrmont.facade.RequestFacade;
import com.framework.tomcat.ex03.pyrmont.facade.ResponseFacade;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

/**
 * @author LIN
 * @date 2022-06-06 21:33
 */
public class ServletProcessor2 {

    /**
     *  处理servlet请求
     * @param request 请求
     * @param response 响应
     */
    public void process(Request request, Response response) {
        String uri = request.getUri();
        String servletName = uri.substring(uri.lastIndexOf("/") + 1);
        URLClassLoader loader = null;
        try{
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File classPath = new File(Constants.WEB_ROOT);
            String repository =(new URL("file", null, classPath.getCanonicalPath()+File.separator)).toString();
            urls[0] = new URL(null, repository, streamHandler);
            loader = new URLClassLoader(urls);

        }catch(Exception e){
            System.err.println(e.toString());
        }
        Class myClass = null;
        try{
            myClass = loader.loadClass(servletName);
        }catch(Exception e){
            System.out.println(e.toString());
        }

        Servlet servlet = null;
        RequestFacade requestFacade = new RequestFacade(request);
        ResponseFacade responseFacade = new ResponseFacade(response);
        try{
            servlet  = (Servlet) myClass.newInstance();
            servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
        }catch(Exception e){
            System.out.println(e.toString());
        }
    }
}
